using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Manager;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;
using System.Collections;
using System.Xml;
using System.Web.UI;

/// <summary>
/// Summary description for update
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
[Serializable()]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class update : System.Web.Services.WebService
{
    public update()
    {
    }
    DbManager db = new DbManager();

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    public Boolean Contact(string name, string email, string subject, string contact)
    {
        DbManager db = new DbManager();
        SqlParameter[] param1 = { 
                new SqlParameter("c_Name",name),
                new SqlParameter("c_Email",email),
                new SqlParameter("c_Subject",subject),
                new SqlParameter("c_Contact",contact)
            };
        Boolean flag = db.changeData("Insert Into Contacts values(@c_Name,@c_Email,@c_Subject,@c_Contact)", param1);

        return flag;
    }

    [WebMethod]
    public ICollection<Product> getProducts(int pageCurrent, int id)
    {
        DataTable dt = new DataTable();
        IList<Product> list = new List<Product>();
        string[] table = { "Products p inner join Categories c on p.p_Categories=c.c_ID" }; //{ "Products p inner join Categories c on s.p_Categories=c.c_ID" };
        if (id > 0)
        {
            SqlParameter[] param1 = { new SqlParameter("p.p_Status", "1"), new SqlParameter("c.c_ID", id) };
            dt = db.tableSearch(pageCurrent, 8, 8, table, param1);
        }
        else
        {
            SqlParameter[] param1 = { new SqlParameter("p.p_Status", "1") };
            dt = db.tableSearch(pageCurrent, 8, 8, table, param1);
        }
        foreach (DataRow row in dt.Rows)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(row["p_Image"].ToString());
            string img = doc.SelectNodes("/images/image[1]")[0].FirstChild.InnerText;
            doc.LoadXml(row["p_Price"].ToString());
            string rd_price = doc.SelectNodes("/price")[0].FirstChild.InnerText;
            string rl_price = doc.SelectNodes("/price")[0].LastChild.InnerText;
            list.Add(new Product() { id = row["p_ID"].ToString(), name = row["p_Name"].ToString(), image = img, reduced_price = rd_price, real_price = rl_price });
        }
        return list;
    }

    [WebMethod]
    public string getPage(string currentURL, int id)
    {
        string[] table = { "Products p inner join Categories c on p.p_Categories=c.c_ID" };
        string ss = "";
        if (id > 0)
        {
            SqlParameter[] param = { new SqlParameter("p.p_Status", "1"), new SqlParameter("c.c_ID", id) };
            ss = db.PageCoutntotalnumberofpages(currentURL, "pageCurrent", 8, table, param);
        }
        else
        {
            SqlParameter[] param = { new SqlParameter("p.p_Status", "1") };
            ss = db.PageCoutntotalnumberofpages(currentURL, "pageCurrent", 8, table, param);
        }
        return ss;
    }
    [WebMethod]
    public string getCategory()
    {
        IList<Category> list = new List<Category>();
        string[] table = { "Categories" };
        SqlParameter[] param1 = { 
                new SqlParameter("c_Status","1")
            };
        DataTable dt = db.getData("select * from Categories where c_Status=@c_Status", param1);
        string s = "";
        foreach (DataRow row in dt.Rows)
        {
            s += "<div id=\"item1\" class=\"repeaterButton\">";
            s += "<a><p class=\"" + row["c_ID"].ToString() + "\">" + row["c_Name"].ToString() + "</p></a></div>";
        }
        return s;
    }
    [WebMethod]
    public ICollection<Product> getProductbyID(int id_Product)
    {
        IList<Product> list = new List<Product>();
        SqlParameter[] param1 = { new SqlParameter("p_ID", id_Product) };
        DataTable dt = db.getData("select * from Products where p_ID=@p_ID", param1);
        foreach (DataRow row in dt.Rows)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(row["p_Image"].ToString());
            string img = doc.SelectNodes("/images/image[1]")[0].FirstChild.InnerText;
            IList<string> list_image = new List<string>();
            IList<string> list_size = new List<string>();
            IList<string> list_color = new List<string>();
            if (doc.SelectNodes("/images/image").Count >= 2)
            {
                foreach (XmlNode node in doc.SelectNodes("/images/image"))
                {
                    list_image.Add(node.FirstChild.InnerText);
                }
            }
            if (row["p_Detail"].ToString() != "")
            {
                doc.LoadXml(row["p_Detail"].ToString());
                if (doc.SelectNodes("details/sizes/size").Count >= 1)
                {
                    foreach (XmlNode node in doc.SelectNodes("details/sizes/size"))
                    {
                        list_size.Add(node.InnerText);
                    }
                }

                if (doc.SelectNodes("details/frames/frame").Count >= 1)
                {
                    foreach (XmlNode node in doc.SelectNodes("details/frames/frame"))
                    {
                        list_color.Add(node.InnerText);
                    }
                }
            }
            doc.LoadXml(row["p_Price"].ToString());
            string rd_price = doc.SelectNodes("/price")[0].FirstChild.InnerText;
            string rl_price = doc.SelectNodes("/price")[0].LastChild.InnerText;
            list.Add(new Product() { id = row["p_ID"].ToString(), name = row["p_Name"].ToString(), image = img, size = list_size, color = list_color, list_image = list_image, reduced_price = rd_price, real_price = rl_price, content = row["p_Content"].ToString() });
        }
        return list;
    }
    [WebMethod]
    public Boolean setGioHang(string id_Product, string size, string color, Boolean status)
    {
        IList<GioHang> gh = new List<GioHang>();
        try
        {
            if (Application["Cart"] == null)
            {
                gh.Add(new GioHang(0, id_Product, size, color, "1", true));
                Application["Cart"] = gh;
                return true;
            }
            else
            {
                gh = (IList<GioHang>)Application["Cart"];//da co san gio hang....
                foreach (GioHang gh_item in gh)
                {//check had cart
                    if (gh_item.id_Product == id_Product && gh_item.size == size && gh_item.color == color)
                    {
                        gh_item.soluong = (int.Parse(gh_item.soluong) + 1).ToString();
                        Application["Cart"] = gh;
                        return true;
                    }
                }
                gh.Add(new GioHang(gh.Count, id_Product, size, color, "1", true));
                Application["Cart"] = gh;
                return true;
            }
        }
        catch
        {
            return false;
        }
    }

    [WebMethod]
    public ICollection<GioHang> getGioHang()
    {
        IList<GioHang> list_Cart = new List<GioHang>();
        if (Application["Cart"] != null)
        {
            list_Cart = (IList<GioHang>)Application["Cart"];
            foreach (GioHang item_Cart in list_Cart)
            {
                DataTable dt = db.getData("select p_Name, p_Image, p_Price, p_Status from Products where p_ID = @p_ID", new SqlParameter("p_ID", item_Cart.id_Product));
                if (dt.Rows.Count == 0 || !((Boolean)dt.Rows[0]["p_Status"]))
                {
                    item_Cart.status = false;
                }
                else
                {
                    item_Cart.name = dt.Rows[0]["p_Name"].ToString();
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(dt.Rows[0]["p_Price"].ToString());
                    item_Cart.gia = doc.SelectNodes("/price")[0].LastChild.InnerText;
                    doc.LoadXml(dt.Rows[0]["p_Image"].ToString());
                    item_Cart.image = doc.SelectNodes("/images/image[1]")[0].FirstChild.InnerText;
                }
            }
            Application["Cart"] = list_Cart;
        }
        return list_Cart;
    }

    [WebMethod]
    public int getTotalCart()
    {
        if (Application["Cart"] == null)
            return 0;
        else
            return ((IList<GioHang>)Application["Cart"]).Count;
    }
    [WebMethod]
    public Boolean delCart(int stt_Cart)
    {
        IList<GioHang> list_Cart = (IList<GioHang>)Application["Cart"];
        foreach (GioHang cart in list_Cart)
        {
            if (cart.stt == stt_Cart)
            {
                int begin = cart.stt;
                list_Cart.Remove(cart);
                for (int i = begin; i < list_Cart.Count; i++)
                {
                    list_Cart[i].stt = i;
                }
                Application["Cart"] = list_Cart;
                return true;
            }
        }
        return false;
    }

    [WebMethod]
    public Boolean updateCart(int stt_Product, int new_count)
    {
        try
        {
            IList<GioHang> list_Cart = (IList<GioHang>)Application["Cart"];
            foreach (GioHang gh in list_Cart)
            {
                if (gh.stt == stt_Product)
                {
                    gh.soluong = new_count.ToString();
                    Application["Cart"] = list_Cart;
                    return true;
                }
            }
            return false;
        }
        catch
        {
            return false;
        }
    }

    [WebMethod(EnableSession = true)]
    public Boolean login(string u, string p)
    {
        try
        {
            DataTable dt = new DataTable();
            SqlParameter[] param = { 
                                   new SqlParameter("u_User", u), 
                                   new SqlParameter("u_Pass", p), 
                                   new SqlParameter("u_Status", 1) 
                               };
            dt = db.getData("select u_ID, u_User, u_Avatar, u_Rull from UserNames where u_User=@u_User and u_Pass=@u_Pass and u_Status=@u_Status", param);
            if (dt.Rows.Count == 1)
            {
                UserName un = new UserName(dt.Rows[0]["u_ID"].ToString(), dt.Rows[0]["u_User"].ToString(), dt.Rows[0]["u_Avatar"].ToString(), dt.Rows[0]["u_Rull"].ToString());
                Context.Session["me"] = un;
                return true;
            }
            else
                return false;
        }
        catch
        {
            return false;
        }
    }
    
    [WebMethod(EnableSession=true)]
    public void Logout() {
        Context.Session["me"] = null;
    }

    [WebMethod(EnableSession = true)]
    public ICollection<UserName> CheckEmptyLogin()
    {
        IList<UserName> list = new List<UserName>();
        if (Context.Session["me"] == null)
            return list;
        else
        {   
            UserName un = (UserName) Context.Session["me"];
            list.Add(un);
            return list;
        }
    }
}